//
//  HttpDownloadManager.m
//  TestDownload
//
//  Created by luffy on 16/3/10.
//  Copyright © 2016年 luffy. All rights reserved.
//

#import "HttpDownloadManager.h"
#import "HttpDownload.h"

@implementation HttpDownloadManager

+ (instancetype)sharedInstance
{
    static HttpDownloadManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[HttpDownloadManager alloc] init];
    });
    return _sharedInstance;
}

-(id)init
{
    if([super init]){
        
        self.taskMap = [NSMutableDictionary dictionary]; 
    }
    return self;
}

//添加下载任务
-(void)addTask:(NSString*)taskName
           Obj:(RequestDownloadTask*)objTask
{
    [self.taskMap setValue:objTask forKey:taskName];
}

//删除下载任务
-(void)delTask:(NSString*)taskName
{
    if([self getTask:taskName]){
        [[self getTask:taskName] stop];
        [self.taskMap removeObjectForKey:taskName];
    }
}

//暂停下载任务
-(void)pauseTask:(NSString*)taskName
{
    if([self getTask:taskName]){
        [[self getTask:taskName] pause];
    }
}

//中断下载任务
-(void)stopTask:(NSString*)taskName
{
    if([self getTask:taskName]){
        [[self getTask:taskName] stop];
    }
}

//删除所有任务
-(void)delAllTask
{
    for (RequestDownloadTask*task in [self.taskMap allValues]) {
        [task stop];
    }
    [self.taskMap removeAllObjects];
}

//停止所有任务
-(void)stopAllTask
{
    for (RequestDownloadTask*task in [self.taskMap allValues]) {
        [task stop];
    }
}

//开始所有任务
-(void)startAllTask
{
    for (NSString*taskName in [self.taskMap allKeys]) {
        [self startTask:taskName];
    }
}

//判断当前任务是否存在
- (BOOL)currentTaskExsit:(NSString *)taskName
{
    for (NSString *taskNameExsit in [self.taskMap allKeys]) {
        if ([taskName isEqualToString:taskNameExsit]) {
            return YES;
        }
    }
    return NO;
}

//开始某个任务
-(void)startTask:(NSString*)taskName
{
    if([self getTask:taskName]){
        RequestDownloadTask* task = [self getTask:taskName];
        [task start];
        
        if(!task.use && [task isStart]){
            task.use = YES;
            [HttpDownload downloadFile:task];
        }
    }
}

//获取某个下载任务
-(RequestDownloadTask*)getTask:(NSString*)taskName
{
    return [self.taskMap objectForKey:taskName];
}

@end
